package com.zs.toolbox.web2j.system.storage.service;

import com.zs.toolbox.web2j.common.exception.WtExceptions;
import com.zs.toolbox.web2j.system.storage.utils.Ftp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.io.InputStream;

/**
 * Copyright ©2016
 *
 * @author shuai.zhang  on 2017/6/2
 * @version 1.0.0
 * @description
 */
@Service
@ConditionalOnProperty(prefix = "wt.storage.ftp", name = "host")
@Slf4j
public class WtFTPStorageServiceImpl implements WtStorageService {

	public WtFTPStorageServiceImpl() {
	    log.info("启动FTP存储器");
	}

	@Value("${wt.storage.ftp.user}")
	String ftpUsername;

	@Value("${wt.storage.ftp.password}")
	String ftpPassword;

	@Value("${wt.storage.ftp.host}")
	String ftpHost;

	@Value("${wt.storage.ftp.prefix}")
	String ftpPathPrefix;

	@Value("${wt.storage.ftp.port}")
	Integer ftpPort;

	public String saveFile(String relativeFullFilePath, InputStream inputStream) {
		Ftp ftp = new Ftp(ftpHost, ftpPort, ftpUsername, ftpPassword);
		boolean b = ftp.ftpLogin();

		if (!b) {
			throw WtExceptions.E_STORAGE_FTP_LOGIN_ERROR;
		}

		try {
			ftp.uploadFile(FilenameUtils.getName(relativeFullFilePath),inputStream,
					String.format("%s/%s",ftpPathPrefix,FilenameUtils.getPath(relativeFullFilePath)));
			return relativeFullFilePath;
		} catch (Exception e) {
			log.error("upload filename ", e);
			throw WtExceptions.E_STORAGE_FTP_UPLOAD;
		} finally {
			ftp.ftpLogOut();
		}
	}
}
